<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片 -->
        <el-card>
            <el-row :gutter="20">
                <!-- 框架栅格系统  span -->
                <el-col :span="10">  
                     <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 用户列表 -->
            <el-table :data="userList" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="220px">
                    <!-- 使用作用域插槽接收一下行内数据  scope 打印出 本行的所有账号数据 -->
                    <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" content="修改" placement="top" size="mini" :enterable="false">
                            <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="删除" placement="top" size="mini" :enterable="false">
                            <el-button type="danger" icon="el-icon-delete" @click="remoUserById(scope.row.id)"></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="分配角色" placement="top" size="mini" :enterable="false">
                            <el-button type="warning" icon="el-icon-star-off" @click="setRole(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1, 2, 5, 10]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
            <!-- 添加用户的对话框 -->
            <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDiologClosed">
                <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="addForm.username"></el-input>
                    </el-form-item>  
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="addForm.password"></el-input>
                    </el-form-item> 
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="addForm.email"></el-input>
                    </el-form-item> 
                    <el-form-item label="手机" prop="mobile">
                        <el-input v-model="addForm.mobile"></el-input>
                    </el-form-item> 
                </el-form>    
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addUser">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 修改用户对话框 -->
            <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
                <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="editForm.username" disabled></el-input>
                    </el-form-item>  
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="editForm.email"></el-input>
                    </el-form-item> 
                    <el-form-item label="手机" prop="mobile">
                        <el-input v-model="editForm.mobile"></el-input>
                    </el-form-item> 
                </el-form>    
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editUseInfo">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>
        <el-dialog title="角色分配" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
            <div>
                <p>当前的用户 {{userInfo.username}}</p>
                <p>当前的角色 {{userInfo.role_name}}</p>
                <p>
                    分配新角色
                    <el-select v-model="selectedRoleId" placeholder="请选择">
                        <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        // 自定义邮箱验证规则
        var chekcEmail = (rule, value, cb) => {
            const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
            if(regEmail.test(value)) {
                // 返回true 验证通过
                return cb()
            }
            cb(new Error('请输入合法邮箱'))
        }
        var checkMobile = (rule, value, cb) => {
            const regMobile = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/
            if(regMobile.test(value)) {
                // 返回true 验证通过
                return cb()
            }
            cb(new Error('请输入合法手机号码'))
        }
        // 自定义手机验证规则
        return {
            queryInfo: {
                query: '',
                // 当前页数
                pagenum: 1,
                // 当前每页显示数据条数
                pagesize: 2
            },
            userList: [],
            total: 0,
            // 添加用户控制弹框隐藏和开启
            addDialogVisible: false,
            // 添加用户数据对象
            addForm: {
                username: '',
                password: '',
                email: '',
                mobile: ''
            },
            // 添加用户数据验证对象
            addFormRules: {
                username: [
                    { required: true, message: '请输入账号名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                    // { pattern: /^[\u4E00-\u9FA5]+$/, message: '用户名只能为中文' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: chekcEmail, trigger: 'blur' }
                
                ],
                mobile: [
                    { required: true, message: '请输入手机', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ]
            },
            editDialogVisible: false,
            editForm: {},
            editFormRules: {},
            // 分配角色窗口开关
            setRoleDialogVisible: false,
            // 分配橘色获取当前行的角色信息
            userInfo: {},
            rolesList: [],
            // 下拉菜单已选中的角色信息
            selectedRoleId: ''
        }
    },
    created() {
        this.getUserList()
    },
    methods: {
        async getUserList() {
            const { data: res } = await this.$http.get('users', { params: this.queryInfo })
            // console.log(res)
            if (res.meta.status !== 200) {
                return this.$message.error('获取用户列表失败')
            }
            this.userList = res.data.users
            this.total = res.data.total
        },
        // 点击每页多少条触发事件
        handleSizeChange(newSize) {
            // 监听页数选择事件，将监听的动态页数赋值给data数据
            this.queryInfo.pagesize = newSize
            // 改变页数后需要刷新数据条数，重新获取数据
            this.getUserList()
        },
        // 点击切换分页时触发的事件
        handleCurrentChange(newPage) {
            this.queryInfo.pagenum = newPage
            this.getUserList()
        },
        // 监听开关的状态
          async userStateChanged (userinfo) {
            const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
            if (res.meta.status !== 200) {
                userinfo.mg_state = !userinfo.mg_state
                return this.$message.error('更新用户状态失败')
            }
            this.$message.success('更新用户状态成功')
        },
        // 监听添加用户表单关闭时触发
        addDiologClosed() {
            // 重置表单, 重置表单方法resetFields() addFormRef重置表单对象
           this.$refs.addFormRef.resetFields() 
        },
        addUser() {
            // 添加用户与验证,点击添加用户后如果什么都不选是无法点击确定的
            this.$refs.addFormRef.validate(async valid => {
                // 填写信息无误点击确定会返回ture
                if(!valid) return
                // post进行数据提交 
               const { data: res } = await this.$http.post('users', this.addForm)
               if(res.meta.status !== 201) {
                //    如果不等于201说明提交失败
                   this.$message.error('添加用户失败')
               }
            //    提交成功
               this.$message.success('添加用户成功')
            //    将弹窗闭关  改为false
               this.addDialogVisible = false
            //    添加成功后需要刷新数据列表
               this.getUserList()
            })
        },
        // 用户编辑 id是通过slot-scope="scope" 自定义插槽  scope.row.id 获取当前行的信息
        async showEditDialog(id) {
            // 发送get请求获取当前编辑的用户信息
            const { data: res } = await this.$http.get('users/' + id)
            if(res.meta.status !== 200) {
                // 获取失败提示
                return this.$message.error('获取用户信息失败')
            }
            // 获取成功后将数据赋值给私有data数据
            this.editForm = res.data
            // 打开编辑窗口
            this.editDialogVisible = true
        },
        // 关闭修改提示框时触发，重置信息
        editDialogClosed() {
            this.$refs.editFormRef.resetFields()
        },
        // 对修改的表单进行与验证
        editUseInfo() {
            this.$refs.editFormRef.validate(async valid => {
                if(!valid) return
                const { data: res } = await this.$http.put('users/' + this.editForm.id, {
                    email: this.editForm.email,
                    mobile: this.editForm.mobile
                })
                if(res.meta.status !== 200) {
                    return this.$message.error('更新用户信息失败')
                }
                // 关闭修改提示框
                this.editDialogVisible = false
                // 刷新数据列表
                this.getUserList()
                // 提示修改成功
                this.$message.success('修改成功')
            })
        },
        // 删除id信息
        async remoUserById(id) {
            const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            // 如果用户点击确定删除，返回字符串confirm
            // 如果用户点击取消删除，返回字符串cancel
            if(confirmResult !== 'confirm') {
                return this.$message.info('已取消删除')
            }
            const { data: res } = await this.$http.delete('users/' + id)
            if(res.meta.status !== 200) {
                return this.$message.error('删除失败')
            }
            this.$message.success('删除成功')
            this.getUserList()
        },
        async setRole(userInfo) {
            this.userInfo = userInfo
            const { data: res } = await this.$http.get('roles')
            if(res.meta.status !== 200) {
                return this.$message.error('获取角色列表失败')
            }
            this.rolesList = res.data
            this.setRoleDialogVisible = true
        },
        async saveRoleInfo() {
            if(!this.selectedRoleId) {
                return this.$message.error('请选择角色')
            }
            const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
            if(res.meta.status !== 200) {
                return this.$message.error('更新角色失败')
            }
            this.$message.success('更新角色成功')
            this.getUserList()
            this.setRoleDialogVisible = false
        },
        // 重置信息，避免打开窗口后存有之前的信息
        setRoleDialogClosed() {
            this.selectedRoleId = ''
            this.userInfo = {}
        }
    }
}
</script>

<style lang="less" scoped>
.el-table {
    margin-top: 15px;
    font-size: 12px;
}
.el-pagination {
    margin-top: 15px;
}
</style>